﻿using MyHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using clf.weighing.entity;
using Brushes = System.Windows.Media.Brushes;

namespace weighing
{
    /// <summary>
    /// LoginWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        #region variables
        public bool IsChangeAccount = false;
        private List<HistoryUser>? historyUsers;
        private bool IsAutoLogin = false;
        private bool IsRemberPwd = false;
        private HistoryUser? hostoryUser;
        #endregion
        public LoginWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
            ShowCustomIcon();
        }

        #region Window Default Event

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SetConfig();
            SetCopyRightText();
        }

        private void Window_ContentRendered(object sender, EventArgs e)
        {
            historyUsers =HistoryUserDao.Instance.GetHistoryUsers();
            if (historyUsers != null && historyUsers.Count > 0)
            {
                this.mobileTb.ItemsSource = historyUsers;
                this.mobileTb.SelectedIndex = 0;
            }

            CheckManager();

            SetDeveloperAccount();
        }

        /// <summary>
        /// window move event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HeaderBorder_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        private void CloseBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsChangeAccount)
            {
                //App.Current.MainWindow?.Close();
            }
        }

        private void Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Escape:
                    this.Close();
                    break;
                case Key.Enter:
                    LoginBtn_Click(sender, e);
                    break;
                default:
                    break;
            }
        }
        #endregion

        private void ShowCustomIcon()
        {
            IconImg.Source = this.Icon;

        }

        /// <summary>
        /// 设置配制 
        /// </summary>
        private void SetConfig()
        {
            App.Config = ConfigDao.Instance.GetLocalConfig();
        }

        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {
          
            string mobile = this.mobileTb.Text.Trim();
            if (String.IsNullOrEmpty(mobile) || mobile.Length < 2)
            {
                string msg = "登录账号不正确";
                this.AlertPanel.Visibility = Visibility;
                this.AlertTb.Text = msg;
                this.mobileTb.BorderBrush = Brushes.Red;
                CommonFunction.SpeakAsync(msg);
                this.LoginBtn.IsChecked = false;
                return;
            }
            string pwdStr = this.pwdPb.Password.Trim();
            if (String.IsNullOrEmpty(pwdStr) || pwdStr.Length < 6)
            {
                string msg = "密码长度至少6位";
                this.AlertPanel.Visibility = Visibility;
                this.AlertTb.Text = msg;
                CommonFunction.SpeakAsync(msg);
                this.pwdPb.BorderBrush = Brushes.Red;
                this.LoginBtn.IsChecked = false;
                return;
            }

            Thread thread = new Thread(new ThreadStart(delegate
            {
                String password = pwdStr;
                if ( pwdStr.Length > 10)
                {         
                    password =EncryptHelper.Decrypto(pwdStr);
                }     
            
                User? user = UserDao.Instance.Login(mobile, password);
                user ??= UserDao.Instance.Login(mobile, EncryptHelper.MD5Encrypt(password));
                this.Dispatcher.Invoke(new Action(delegate
                {
                    if (user != null)
                    {                       
                        user.Permissions =PermissionDao.Instance.GetUserPermissions((long)user.id);
                        App.CurrentUser = user;
                        DoubleAnimation animation = new ()
                        {
                            From = 0,
                            To = 1,
                            Duration = new Duration(TimeSpan.FromMilliseconds(800))
                        };
                        CommonFunction.SpeakAsync("登录成功");                       
                        animation.Completed += Animation_Completed;
                        this.BeginAnimation(OpacityProperty, animation);
                    }
                    else
                    {
                        string msg = "登录失败账号或者密码错误";
                        this.AlertPanel.Visibility = Visibility;
                        this.AlertTb.Text = msg;
                        CommonFunction.SpeakAsync(msg);
                        this.mobileTb.BorderBrush = Brushes.Red;
                        this.LoginBtn.IsChecked = false;
                        return;
                    }
                }), System.Windows.Threading.DispatcherPriority.Normal);

            }));
            thread.Start();
        }
        //登录成功后 进入主界面
        private void Animation_Completed(object sender, EventArgs e)
        {
            this.Hide();         
            new MainWindow().Show();          
            this.Close();
            new Thread(new ThreadStart(SaveToFile)).Start();
        }

        private void RemberPwdCBox_Checked(object sender, RoutedEventArgs e)
        {
            IsRemberPwd = true;
        }

        private void RemberPwdCBox_Unchecked(object sender, RoutedEventArgs e)
        {
            IsRemberPwd = false;
            if (hostoryUser != null)
            {
                hostoryUser.IsAutoLogin = false;
                this.pwdPb.Password = String.Empty;
            }
            this.AutoLoginCbox.IsChecked = false;
        }

        private void AutoLoginCbox_Checked(object sender, RoutedEventArgs e)
        {
            IsAutoLogin = true;

            this.RemberPwdCBox.IsChecked = true;
        }

        private void AutoLoginCbox_Unchecked(object sender, RoutedEventArgs e)
        {
            IsAutoLogin = false;
            if (hostoryUser != null)
            {
                hostoryUser.IsAutoLogin = false;
            }
        }

        private void SaveToFile()
        {
            if (App.CurrentUser?.roleType == (int)UserRoleType.Developer)
            {
                //开发人员的账号，不缓存
                return;
            }

            HistoryUserDao.Instance.SaveUser(App.CurrentUser, this.IsAutoLogin, this.IsRemberPwd);
        }


        private void MobileTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.IsLoaded)
            {
                String str = this.mobileTb.Text.Trim();
                if (str.Length <= 0)
                {
                    this.mobileTb.SelectedIndex = -1;
                    this.RemberPwdCBox.IsChecked = false;
                    this.AutoLoginCbox.IsChecked = false;
                    this.pwdPb.Password = String.Empty;
                }
            }
        }

        private void MobileTb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (mobileTb.SelectedIndex < 0)
            {
                hostoryUser = null;
                this.mobileTb.Text = "";
                this.pwdPb.Password = "";
                return;
            }
            hostoryUser = this.mobileTb.SelectedItem as HistoryUser;
            if (hostoryUser == null)
            {
                return;
            }
            if (hostoryUser.IsRemberPwd)
            {
                this.pwdPb.Password = hostoryUser.Pwd;
            }
            this.mobileTb.Text = hostoryUser.Phone;
            this.RemberPwdCBox.IsChecked = hostoryUser.IsRemberPwd;
            this.AutoLoginCbox.IsChecked = hostoryUser.IsAutoLogin;
            this.IsAutoLogin = hostoryUser.IsAutoLogin;
            if (hostoryUser.IsRemberPwd && !string.IsNullOrEmpty(hostoryUser.Pwd))
            {
                //MD5
                this.pwdPb.Password = hostoryUser.Pwd;
            }
            if (hostoryUser.IsRemberPwd == true && hostoryUser.IsAutoLogin == true)
            {
                if (IsChangeAccount == false)
                {
                    LoginBtn_Click(null, null);
                }
            }
        }

        private void FergotPwdTb_Click(object sender, RoutedEventArgs e)
        {
            CommonFunction.AlertInfo("联系管理员进行重置密码");
        }
        //显示和关闭工具Popup
        private void Toolsbtn_Click(object sender, RoutedEventArgs e)
        {
            this.ToolsPopup.IsOpen = !this.ToolsPopup.IsOpen;
        }
        //测试磅称数据读取
        private void TestScale_Click(object sender, RoutedEventArgs e)
        {
            new TestScaleWindow() { WindowStartupLocation = WindowStartupLocation.CenterScreen }.ShowDialog();
        }
     
        /// <summary>
        /// 设置版权文字
        /// </summary>
        private void SetCopyRightText()
        {
            string copyRight = App.Config.SystemConfig.CopyRight;

            copyRight += " 单机1.0";
            
            this.copyrightTB.Text = copyRight;
        }
        /// <summary>
        /// 为开发节省时间，设置一个开发账号
        /// </summary>
        private void SetDeveloperAccount()
        {
#if DEBUG
            this.mobileTb.SelectedIndex = -1;
            this.mobileTb.Text = "18087467482";
            this.pwdPb.Password = "bn.123456";
#endif
        }
        /// <summary>
        /// 检查管理员是否已经有
        /// </summary>
        private void CheckManager()
        {
            //调试模式下都显示
            if (App.Config.SystemConfig.Debug) return;
            if (UserDao.Instance.IsHasManager())
            {
                this.NoManagerWP.Visibility = Visibility.Collapsed;
                this.loginPanel.Visibility = Visibility.Visible;
            }
            else
            {
                this.NoManagerWP.Visibility = Visibility.Visible;
                this.loginPanel.Visibility = Visibility.Hidden;
            }

        }
        //添加系统管理员
        private void AddLink_Click(object sender, RoutedEventArgs e)
        {
            bool? res = new UserAddWindow() { Owner = this }.ShowDialog();
            if (res.HasValue && res.Value == true) CheckManager();
        }

        private void ClearHistoryUserTb_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                File.Delete(Constant.HUserFilePath);
                this.historyUsers?.Clear();
                this.mobileTb.ItemsSource = null;
            }
            catch (Exception)
            {
            }
        }


    }
}
